﻿using System.Threading.Tasks;
using Caltech.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Caltech.Results;
using CaltechSoft.Service.CommandService;
using ServiceModel = CaltechSoft.Service.DBCommand;
using AutoMapper;
using CaltechSoft.Service.ReportService;
using CaltechSoft.Service.SearchCriteria;
using CaltechSoft.Service.Repositories;
using CaltechSoft.Service.EntityFW.Entity;
using System.Linq.Expressions;
using LinqKit;
using Caltech.Extensions;
using Caltech.Service.Common;

namespace Caltech.Controllers
{
    [HasAccess(Areas.EquipmentView)]
    public class EquipmentController : BaseApiController<Equipment, EquipmentModel, EquipmentModel>
    {
        public EquipmentController(IRepository<Equipment> repository)
            : base(repository)
        {

        }

        [HasAccess(Areas.EquipmentView)]
        public override IHttpActionResult Get()
        {
            var queryItems = Request.RequestUri.ParseQueryString();
            var predicate = PredicateBuilder.True<Equipment>();

            if (queryItems["model"] != null)
            {
                var model = queryItems["model"].ToLower();
                predicate = predicate.And(equipment => equipment.ModelNumber.ToLower().Contains(model.Trim()));
            }
            if (queryItems["description"] != null)
            {
                var description = queryItems["description"].ToLower();
                predicate = predicate.And(equipment => equipment.Name.ToLower().Contains(description.Trim()));
            }

            return QueryData(predicate);
        }

        [HttpGet]
        [Route("api/equipment/validate")]
        public IHttpActionResult Validate(string model, string manufacturer, int? id = null)
        {
            return ValidateData(equipment =>
                equipment.ModelNumber.Equals(model, StringComparison.CurrentCultureIgnoreCase) &&
                equipment.Manufacturer.Equals(manufacturer, StringComparison.CurrentCultureIgnoreCase) &&
                equipment.Id != id
                );
        }

        [HasAccess(Areas.EquipmentView)]
        public override async Task<IHttpActionResult> GetBy(int id)
        {
            return await base.GetBy(id);
        }

        [HasAccess(Areas.EquipmentCreate)]
        public override async Task<IHttpActionResult> Post(EquipmentModel model)
        {
            return await base.Post(model);
        }

        [HasAccess(Areas.EquipmentEdit)]
        public override async Task<IHttpActionResult> Put(EquipmentModel model)
        {
            return await base.Put(model);
        }

        [HasAccess(Areas.EquipmentDelete)]
        public override async Task<IHttpActionResult> Delete(int id)
        {
            return await base.Delete(id);
        }
    }
}